/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.inputQuestion;

import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.Validate;

import ru.irenproject.AbstractQuestionEditor;
import ru.irenproject.Action;
import ru.irenproject.Question;
import ru.irenproject.TestInputException;
import ru.irenproject.Utils;
import ru.irenproject.pad.PadEditor;
import ru.irenproject.store.AspectId;
import ru.irenproject.store.Event;
import ru.irenproject.store.Initializer;
import ru.irenproject.store.Stash;
import ru.irenproject.store.Thing;

import com.google.protobuf.Message;

public final class InputQuestionEditor extends AbstractQuestionEditor {
  public static final class DeletePatternInput {
    public int index;
  }

  public static final class MovePatternInput {
    public int index;
    public boolean forward;
  }

  private final static AspectId ASPECT_ID = new AspectId(0x6b32934caf30f8d9L);

  @Stash private InputQuestionProtos.InputQuestionEditor.Builder $;

  private final Map<Class<? extends Pattern>, Class<? extends AbstractPatternEditor>> fEditorClasses;

  @Inject InputQuestionEditor(Map<Class<? extends Pattern>, Class<? extends AbstractPatternEditor>> editorClasses) {
    fEditorClasses = editorClasses;
  }

  @Override public InputQuestion question() {
    return get($.getQuestion(), InputQuestion.class);
  }

  @Override protected void setQuestion(Question question) {
    Validate.isInstanceOf(InputQuestion.class, question);
    $.setQuestion(question.id());
    $.setFormulationEditor(PadEditor.create(question().formulation()).id());
    syncPatternEditors();
    question().addListener(this);
  }

  private void syncPatternEditors() {
    $.clearPatternEditor();
    for (Pattern p : question().patternList()) {
      $.addPatternEditor(open(p).id());
    }
  }

  private PatternEditor open(final Pattern p) {
    Class<? extends AbstractPatternEditor> editorClass = Validate.notNull(fEditorClasses.get(p.getClass()));
    return Utils.requireAspect(p, ASPECT_ID, editorClass, new Initializer<AbstractPatternEditor>() {
      @Override public void initialize(AbstractPatternEditor target) {
        target.setPattern(p);
      }
    });
  }

  @Override public Message render() {
    return InputQuestionProtos.InputQuestionEditorShape.newBuilder()
        .setFormulationEditor($.getFormulationEditor())
        .addAllPatternEditor($.getPatternEditorList())
        .setMaxPatterns(InputQuestion.MAX_PATTERNS)
        .build();
  }

  @Action(badInput = TestInputException.class)
  public void doAddTextPattern() {
    prepareNewPattern(question().addTextPattern());
  }

  @Action(badInput = TestInputException.class)
  public void doAddRegexpPattern() {
    prepareNewPattern(question().addRegexpPattern());
  }

  private void prepareNewPattern(Pattern p) {
    if (question().patternCount() >= 2) {
      Pattern previous = question().patterns(question().patternCount() - 2);
      p.setQualityPercent(previous.qualityPercent());
      p.setOptionsFrom(previous);
    }
  }

  @Override protected void handleEvent(Event e, Thing source) {
    if (e instanceof InputQuestion.ChangeEvent) {
      syncPatternEditors();
    }
  }

  @Action(badInput = TestInputException.class)
  public void doDeletePattern(DeletePatternInput in) {
    question().deletePattern(in.index);
  }

  @Action(badInput = TestInputException.class)
  public void doMovePattern(MovePatternInput in) {
    question().movePattern(in.index, in.forward);
  }
}
